{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bf527085",
   "metadata": {},
   "source": [
    "# 第四节：自动微分\n",
    "在进行梯度下降时需要使用到微分操作，AI框架为我们提供了自动微分的操作。\n",
    "我们拿一个简单的函数举例：\n",
    "$$f(x)=wx+b \\tag {1} $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "50be8db0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mindspore as ms\n",
    "import numpy as np\n",
    "import mindspore.nn as nn\n",
    "import mindspore.ops as ops\n",
    "from mindspore import Parameter as parameter"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5610ac0",
   "metadata": {},
   "source": [
    "## 一、求一阶导\n",
    "首先我们要定义这个函数类："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "7c825756",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Function(nn.Cell):\n",
    "    \"\"\"函数类\"\"\"\n",
    "    def __init__(self):\n",
    "        super(Function, self).__init__()\n",
    "        # 设置权重\n",
    "        self.w = parameter(ms.Tensor(np.array([5.0]), ms.float32), name='w')\n",
    "        self.b = parameter(ms.Tensor(np.array([3.0]), ms.float32), name='b')\n",
    "        \n",
    "    def construct(self, x):\n",
    "        # 定义函数\n",
    "        f = self.w * x + self.b\n",
    "        return f"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36c45591",
   "metadata": {},
   "source": [
    "在MindSpore中，我们可以使用ops.GradOperation来实现自动微分，其有三个可选参数：`get_all, get_by_list和sens_param`。三个参数默认为False。\n",
    "\n",
    "当`get_all`为`False`时，只会对第一个输入求导，为`True`时，会对所有输入求导。\n",
    "\n",
    "当`get_by_list`为`Ture`时，表示对权重进行求导。\n",
    "\n",
    "当`sens_param`为`Ture`时，表示进行梯度缩放。\n",
    "\n",
    "我们需要定义求导的类："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "80876230",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Grad(nn.Cell):\n",
    "    \"\"\"求导类\"\"\"\n",
    "    def __init__(self, function):\n",
    "        super(Grad, self).__init__()\n",
    "        self.function = function\n",
    "        self.grad = ops.GradOperation()\n",
    "        \n",
    "    def construct(self, x):\n",
    "        f = self.grad(self.function)\n",
    "        return f(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22bedff8",
   "metadata": {},
   "source": [
    "我们来尝试计算一下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "026eae78",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5.]\n"
     ]
    }
   ],
   "source": [
    "x = ms.Tensor(np.array([2.0]), ms.float32)\n",
    "output = Grad(Function())(x)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7125314",
   "metadata": {},
   "source": [
    "## 二、对权重求导\n",
    "当我们把`ops.GradOperation`中的参数`get_by_list`设置为`True`时，表示对权重进行求导。我们重新定义求导类："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "76fbc3ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(Tensor(shape=[1], dtype=Float32, value= [3.00000000e+000]), Tensor(shape=[1], dtype=Float32, value= [1.00000000e+000]))\n",
      "对w的求导为： [3.]\n",
      "对b的求导为： [1.]\n"
     ]
    }
   ],
   "source": [
    "class Grad(nn.Cell):\n",
    "    \"\"\"求导类\"\"\"\n",
    "    def __init__(self, function):\n",
    "        super(Grad, self).__init__()\n",
    "        self.function = function\n",
    "        # 对权重求导要加上params这个参数\n",
    "        self.params = ms.ParameterTuple(function.trainable_params())\n",
    "        self.grad = ops.GradOperation(get_by_list=True)\n",
    "        \n",
    "    def construct(self, x):\n",
    "        # 加上params这个参数\n",
    "        f = self.grad(self.function, self.params)\n",
    "        return f(x)\n",
    "    \n",
    "x = ms.Tensor(np.array([3.0]), ms.float32)\n",
    "output = Grad(Function())(x)\n",
    "print(output)\n",
    "print(\"对w的求导为：\", output[0])\n",
    "print(\"对b的求导为：\", output[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56ba3536",
   "metadata": {},
   "source": [
    "如果我们不想对某些权重进行求导，在定义函数类时，可以将其的属性`requires_grad`设置为`False`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "b13d383e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(Tensor(shape=[1], dtype=Float32, value= [1.00000000e+000]),)\n"
     ]
    }
   ],
   "source": [
    "class Function(nn.Cell):\n",
    "    \"\"\"函数类\"\"\"\n",
    "    def __init__(self):\n",
    "        super(Function, self).__init__()\n",
    "        # 将w的requires_grad设置为False\n",
    "        self.w = parameter(ms.Tensor(np.array([5.0]), ms.float32), name='w', requires_grad=False)\n",
    "        self.b = parameter(ms.Tensor(np.array([3.0]), ms.float32), name='b')\n",
    "        \n",
    "    def construct(self, x):\n",
    "        f = self.w * x + self.b\n",
    "        return f\n",
    "\n",
    "    \n",
    "class Grad(nn.Cell):\n",
    "    \"\"\"求导类\"\"\"\n",
    "    def __init__(self, function):\n",
    "        super(Grad, self).__init__()\n",
    "        self.function = function\n",
    "        self.params = ms.ParameterTuple(function.trainable_params())\n",
    "        self.grad = ops.GradOperation(get_by_list=True)\n",
    "        \n",
    "    def construct(self, x):\n",
    "        f = self.grad(self.function, self.params)\n",
    "        return f(x)\n",
    "    \n",
    "x = ms.Tensor(np.array([3.0]), ms.float32)\n",
    "output = Grad(Function())(x)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2157a3ce",
   "metadata": {},
   "source": [
    "## 三、缩放梯度\n",
    "当梯度非常小时，我们可以先将梯度放大进行运算。当我们把`ops.GradOperation`中的参数`sens_param`设置为`True`时，表示可以对梯度进行放缩。我们来重新定义求导类："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "859ec18b",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[50.]\n"
     ]
    }
   ],
   "source": [
    "class Grad(nn.Cell):\n",
    "    \"\"\"求导类\"\"\"\n",
    "    def __init__(self, function):\n",
    "        super(Grad, self).__init__()\n",
    "        self.function = function\n",
    "        # 将sen_param设置为True\n",
    "        self.grad = ops.GradOperation(sens_param=True)\n",
    "        # 设置缩放指数\n",
    "        self.time = ms.Tensor(np.array([10]), ms.float32)\n",
    "        \n",
    "    def construct(self, x):\n",
    "        f = self.grad(self.function)\n",
    "        # 返回时参数加入缩放指数\n",
    "        return f(x, self.time)\n",
    "\n",
    "x = ms.Tensor(np.array([3.0]), ms.float32)\n",
    "output = Grad(Function())(x)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0cfdf351",
   "metadata": {},
   "source": [
    "## 四、停止微分\n",
    "当我们需要停止梯度计算时，可以使用`ops.stop_gradient`算子。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "c9cb9bf9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.]\n"
     ]
    }
   ],
   "source": [
    "from mindspore.ops import stop_gradient as stop\n",
    "\n",
    "class Function(nn.Cell):\n",
    "    \"\"\"函数类\"\"\"\n",
    "    def __init__(self):\n",
    "        super(Function, self).__init__()\n",
    "        self.w = parameter(ms.Tensor(np.array([5.0]), ms.float32), name='w')\n",
    "        self.b = parameter(ms.Tensor(np.array([3.0]), ms.float32), name='b')\n",
    "        \n",
    "    def construct(self, x):\n",
    "        f = self.w * x + self.b\n",
    "        # 停止梯度更新\n",
    "        f = stop(f)\n",
    "        return f\n",
    "    \n",
    "    \n",
    "class Grad(nn.Cell):\n",
    "    \"\"\"求导类\"\"\"\n",
    "    def __init__(self, function):\n",
    "        super(Grad, self).__init__()\n",
    "        self.function = function\n",
    "        self.grad = ops.GradOperation()\n",
    "        \n",
    "    def construct(self, x):\n",
    "        f = self.grad(self.function)\n",
    "        return f(x)\n",
    "    \n",
    "x = ms.Tensor(np.array([3.0]), ms.float32)\n",
    "output = Grad(Function())(x)\n",
    "print(output)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mindspore",
   "language": "python",
   "name": "mindvision"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
